package com.example.retrofit;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;


import com.example.retrofit.Log.HttpLogger;
import com.example.retrofit.Log.ResultClass;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by apple on 16/8/20.
 */
public class HttpClient<T,B,R> {

    private static Context mContext;
    public final int SET_TIME = 60;
    private Class<B> server;
    public  Class resultclass=NullClass.class;
    Interceptor mInterceptor=null;
    public HttpClient(Context context) {
        mContext = context;

    }
    public HttpClient setClass(Class<B> server,Class<R> result){
        this.server=server;
        this.resultclass=result;
        return this;
    }

    public HttpClient setClass(Class<B> server){
        this.server=server;
        return this;
    }
    //添加拦截器
    public HttpClient setInterceptor(Interceptor mInterceptor){
        this.mInterceptor=mInterceptor;
        return this;
    }

    /**
     * 请求数据
     * @param responseHandler 接口回调
     */
    public void request(Call<T> call, final ResponseHandler<T,R> responseHandler) {
        call.enqueue(new Callback<T>() {

            @Override
            public void onResponse(Call<T> call, Response<T> response) {
                if (response.isSuccessful()) {
                    responseHandler.onSuccess(response.body());
                } else {
                    String errorString = null;
                    try {
                        errorString = response.errorBody().string();
                        responseHandler.onFaileMsg(errorString);
                    } catch (IOException e) {
                        responseHandler.onFaileMsg("未知错误！");
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(Call<T> call, Throwable t) {
                //失败返回结果解析
                if (t instanceof ResultClass){
                    responseHandler.onFailure((R)((ResultClass) t).getObject());
                }else {
                    responseHandler.onFaileMsg( t.getMessage());
                }
            }
        });
    }

    public B service(String baseUrl){
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client ;

        //region 网络设置
        if (mInterceptor!=null){
            client = new OkHttpClient.Builder()
                    .addInterceptor(mInterceptor)   //添加拦截器
                    //.addInterceptor(logInterceptor)
                    .addNetworkInterceptor(logInterceptor)
                    .connectTimeout(SET_TIME, TimeUnit.SECONDS)    //连接超时设置
                    .writeTimeout(SET_TIME, TimeUnit.SECONDS)      //读写超时设置
                    .readTimeout(SET_TIME, TimeUnit.SECONDS)
                    .build();

        }else{
            client = new OkHttpClient.Builder()
                    //.addInterceptor(mInterceptor)   //添加拦截器
                    //.addInterceptor(logInterceptor)
                    .addNetworkInterceptor(logInterceptor)
                    .connectTimeout(SET_TIME, TimeUnit.SECONDS)    //连接超时设置
                    .writeTimeout(SET_TIME, TimeUnit.SECONDS)      //读写超时设置
                    .readTimeout(SET_TIME, TimeUnit.SECONDS)
                    .build();
        }
        //endregion

        Retrofit sRetrofit;

        //region 判断是否有统计返回解析
        if (resultclass==NullClass.class){
                    sRetrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(new NullOnEmptyConverterFactory())
                    .addConverterFactory(StringConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())  //json自动转换器
                    //如果有统一的出错返回结果解析
                    //.addConverterFactory(MyGsonConverterFactory.create(resultclass))  //json自动转换器
                    .client(client)
                    .build();
        }else{
                    sRetrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(new NullOnEmptyConverterFactory())
                    .addConverterFactory(StringConverterFactory.create())
                    //.addConverterFactory(GsonConverterFactory.create())  //json自动转换器
                    //如果有统一的出错返回结果解析
                    .addConverterFactory(MyGsonConverterFactory.create(resultclass))  //json自动转换器
                    .client(client)
                    .build();
        }
        //endregion


        return sRetrofit.create(server);
    }


    /**
     * 利用拦截器更改Request请求
     */
    private Interceptor REWRITE_REQUEST_INTERCEPTOR = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {

            Request original = chain.request();
            Request request;
            Request.Builder builder = original.newBuilder();
            request = builder
                    .addHeader("Device", "android")
                    .addHeader("Version", HttpClient.getAppVersionName(mContext))
                    .build();
            okhttp3.Response response = chain.proceed(request);

            return response;
        }
    };

    public static String getAppVersionName(Context context) {
        String versionName = null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            e.printStackTrace();
            versionName = "0.0.0";
        }
        return versionName;
    }



}
